const express = require("express")
const path = require("path")
const logger = require("morgan")
const FileStreamRotator = require("file-stream-rotator")
const fs = require("fs")

const route = require("./routes")

const app = express()

// view engine setup
app.set("views", path.join(__dirname, "views"))
app.set("view engine", "ejs")

// 日志目录：若不存在则创建
var logDirectory = path.join(__dirname, "morgan_log")
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)

// 借助 file-stream-rotator 插件，完成日志分割的工作
var accessLogStream = FileStreamRotator.getStream({
  date_format: "YYYYMMDD",
  filename: path.join(logDirectory, "access-%DATE%.log"),
  frequency: "daily",
  verbose: false,
})

// 根据环境使用不同的日志记录方式
if (process.env.NODE_ENV === 'development') {
  app.use(logger("dev"))
} else if (process.env.NODE_ENV === 'production') {
  app.use(logger("combined", { stream: accessLogStream }))
}

app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, "public")))

// 跨域
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*") // 允许任意地址访问
  res.header("Access-Control-Allow-Methods", "GET, POST")
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization")
  next() // 继续下一个中间件的处理
})

// API
route(app)

module.exports = app
